package com.leyou.cart.mq;

import com.leyou.cart.service.impl.ICartServiceImpl;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 处理请求和响应的方法
 *
 * @version V1.0
 * @package com.leyou.cart.mq
 * @description:
 * @author: pc
 * @date: 2019/7/14 19:12
 */
@Slf4j
@Component
public class CartListenter {
    @Autowired
    private ICartServiceImpl cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.CART_DELETE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.Exchange.CART_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.CART_DELETE_KEY

    ))
    public void deleteCartItem(Map<String,Object> msg) {
        try {
            if (CollectionUtils.isEmpty(msg)) {
                throw new RuntimeException("商品id为空");
            }
            String userId = (String) msg.get("userId");
            List<Long> skuIdList = (List<Long>) msg.get("skuIdList");
            for (Long skuId : skuIdList) {
                cartService.deleteCart(userId,skuId);
            }
        } catch (RuntimeException e) {
            log.error("删除商品失败,原因{}",e.getMessage(),e);
        }
    }

}
